<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blogwebpage/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blogwebpage/images/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/blogwebpage/images/favicon.ico">
  <link rel="mask-icon" href="/blogwebpage/images/logo.svg" color="#222">
  <meta name="msvalidate.01" content="9BDlx6FiNE">

<link rel="stylesheet" href="/blogwebpage/css/main.css">


<link rel="stylesheet" href="/blogwebpage/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"wangkejie.gitee.io","root":"/blogwebpage/","scheme":"Gemini","version":"7.8.0","exturl":true,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"default"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="1、不用中间变量,用两种方法交换A和B的值1234567891011121314151617181920&#x2F;&#x2F; 1.中间变量void swap(int a, int b) &amp;#123;   int temp &#x3D; a;   a &#x3D; b;   b &#x3D; temp;&amp;#125;&#x2F;&#x2F; 2.加法void swap(int a, int b) &amp;#123;   a &#x3D; a + b;   b &#x3D; a - b;">
<meta property="og:type" content="article">
<meta property="og:title" content="iOS 算法收集">
<meta property="og:url" content="https://wangkejie.gitee.io/blogwebpage/iOS/algorithm/index.html">
<meta property="og:site_name" content="王科杰">
<meta property="og:description" content="1、不用中间变量,用两种方法交换A和B的值1234567891011121314151617181920&#x2F;&#x2F; 1.中间变量void swap(int a, int b) &amp;#123;   int temp &#x3D; a;   a &#x3D; b;   b &#x3D; temp;&amp;#125;&#x2F;&#x2F; 2.加法void swap(int a, int b) &amp;#123;   a &#x3D; a + b;   b &#x3D; a - b;">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/13252132-681296a63ca929e4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/13252132-b3d7480416c4f332.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="article:published_time" content="2015-07-10T04:24:27.000Z">
<meta property="article:modified_time" content="2021-06-25T08:55:53.141Z">
<meta property="article:author" content="Jack Wang">
<meta property="article:tag" content="iOS算法收集">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/13252132-681296a63ca929e4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">

<link rel="canonical" href="https://wangkejie.gitee.io/blogwebpage/iOS/algorithm/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>iOS 算法收集 | 王科杰</title>
  


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?93e26277de0cf2c5851167f2c6dcaa7d";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blogwebpage/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">王科杰</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Jack's Notes</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/blogwebpage/" rel="section"><i class="home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blogwebpage/archives/" rel="section"><i class="archive fa-fw"></i>归档<span class="badge">52</span></a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blogwebpage/me/" rel="section"><i class="user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blogwebpage/tags/" rel="section"><i class="tags fa-fw"></i>标签<span class="badge">54</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blogwebpage/categories/" rel="section"><i class="th fa-fw"></i>分类<span class="badge">56</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <span class="exturl github-corner" data-url="aHR0cHM6Ly9naXRodWIuY29tL0phY2stVmluZw==" title="Follow me on GitHub" aria-label="Follow me on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></span>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wangkejie.gitee.io/blogwebpage/iOS/algorithm/index.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blogwebpage/images/avatar.gif">
      <meta itemprop="name" content="Jack Wang">
      <meta itemprop="description" content="书山有路勤为径，学海无涯苦作舟！">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="王科杰">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          iOS 算法收集
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2015-07-10 12:24:27" itemprop="dateCreated datePublished" datetime="2015-07-10T12:24:27+08:00">2015-07-10</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/iOS%E7%AE%97%E6%B3%95/" itemprop="url" rel="index"><span itemprop="name">iOS算法</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="1、不用中间变量-用两种方法交换A和B的值"><a href="#1、不用中间变量-用两种方法交换A和B的值" class="headerlink" title="1、不用中间变量,用两种方法交换A和B的值"></a><strong>1、不用中间变量,用两种方法交换A和B的值</strong></h2><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 1.中间变量</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">swap</span><span class="params">(<span class="keyword">int</span> a, <span class="keyword">int</span> b)</span> </span>&#123;</span><br><span class="line">   <span class="keyword">int</span> temp = a;</span><br><span class="line">   a = b;</span><br><span class="line">   b = temp;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 2.加法</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">swap</span><span class="params">(<span class="keyword">int</span> a, <span class="keyword">int</span> b)</span> </span>&#123;</span><br><span class="line">   a = a + b;</span><br><span class="line">   b = a - b;</span><br><span class="line">   a = a - b;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 3.异或（相同为0，不同为1. 可以理解为不进位加法）</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">swap</span><span class="params">(<span class="keyword">int</span> a, <span class="keyword">int</span> b)</span> </span>&#123;</span><br><span class="line">   a = a ^ b;</span><br><span class="line">   b = a ^ b;</span><br><span class="line">   a = a ^ b;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="2、求最大公约数"><a href="#2、求最大公约数" class="headerlink" title="2、求最大公约数"></a><strong>2、求最大公约数</strong></h2><figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** 1.直接遍历法 */</span></span><br><span class="line"><span class="built_in">int</span> maxCommonDivisor(<span class="built_in">int</span> a, <span class="built_in">int</span> b) &#123;</span><br><span class="line">    <span class="built_in">int</span> max = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="built_in">int</span> i = <span class="number">1</span>; i &lt;=b; i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (a % i == <span class="number">0</span> &amp;&amp; b % i == <span class="number">0</span>) &#123;</span><br><span class="line">            max = i;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> max;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/** 2.辗转相除法 */</span></span><br><span class="line"><span class="built_in">int</span> maxCommonDivisor(<span class="built_in">int</span> a, <span class="built_in">int</span> b) &#123;</span><br><span class="line">    <span class="built_in">int</span> r;</span><br><span class="line">    <span class="keyword">while</span>(a % b &gt; <span class="number">0</span>) &#123;</span><br><span class="line">        r = a % b;</span><br><span class="line">        a = b;</span><br><span class="line">        b = r;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> b;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 扩展：最小公倍数 = (a * b)/最大公约数</span></span><br></pre></td></tr></table></figure>

<h2 id="3、模拟栈操作"><a href="#3、模拟栈操作" class="headerlink" title="3、模拟栈操作"></a><strong>3、模拟栈操作</strong></h2><ul>
<li>栈是一种数据结构，特点：先进后出 -</li>
<li>练习：使用全局变量模拟栈的操作</li>
</ul>
<p><strong>#include &lt;stdio.h&gt;<br>#include &lt;stdbool.h&gt;<br>#include &lt;assert.h&gt;</strong></p>
<p>//保护全局变量：在全局变量前加static后，这个全局变量就只能在本文件中使用<br>static int data[1024];//栈最多能保存1024个数据<br>static int count = 0;//目前已经放了多少个数(相当于栈顶位置)</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//数据入栈 push</span></span><br><span class="line"><span class="keyword">void</span> <span class="function"><span class="title">push</span>(<span class="params">int x</span>)</span>&#123;</span><br><span class="line">    assert(!full());<span class="comment">//防止数组越界</span></span><br><span class="line">    data[count++] = x;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//数据出栈 pop</span></span><br><span class="line">int <span class="function"><span class="title">pop</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    assert(!empty());</span><br><span class="line">    <span class="keyword">return</span> data[--count];</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//查看栈顶元素 top</span></span><br><span class="line">int <span class="function"><span class="title">top</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    assert(!empty());</span><br><span class="line">    <span class="keyword">return</span> data[count-<span class="number">1</span>];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//查询栈满 full</span></span><br><span class="line">bool <span class="function"><span class="title">full</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="function"><span class="title">if</span>(<span class="params">count &gt;= <span class="number">1024</span></span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">     <span class="keyword">return</span> <span class="number">0</span>; </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//查询栈空 empty</span></span><br><span class="line">bool <span class="function"><span class="title">empty</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="function"><span class="title">if</span>(<span class="params">count &lt;= <span class="number">0</span></span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">int <span class="function"><span class="title">main</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="comment">//入栈</span></span><br><span class="line">    <span class="keyword">for</span> (int i = <span class="number">1</span>; i &lt;= <span class="number">10</span>; i++) &#123;</span><br><span class="line">        push(i);</span><br><span class="line">    &#125;</span><br><span class="line">  </span><br><span class="line">    <span class="comment">//出栈</span></span><br><span class="line">    <span class="function"><span class="title">while</span>(<span class="params">!empty()</span>)</span>&#123;</span><br><span class="line">        printf(<span class="string">&quot;%d &quot;</span>, top()); <span class="comment">//栈顶元素</span></span><br><span class="line">        pop(); <span class="comment">//出栈</span></span><br><span class="line">    &#125;</span><br><span class="line">    printf(<span class="string">&quot;\n&quot;</span>);</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="4、排序算法"><a href="#4、排序算法" class="headerlink" title="4、排序算法"></a><strong>4、排序算法</strong></h2><p>选择排序、冒泡排序、插入排序三种排序算法可以总结为如下：<br>都将数组分为已排序部分和未排序部分。</p>
<p>1.选择排序将已排序部分定义在左端，然后选择未排序部分的最小元素和未排序部分的第一个元素交换。</p>
<p>2.冒泡排序将已排序部分定义在右端，在遍历未排序部分的过程执行交换，将最大元素交换到最右端。</p>
<p>3.插入排序将已排序部分定义在左端，将未排序部分元的第一个元素插入到已排序部分合适的位置。</p>
<p><strong>4.1、选择排序</strong></p>
<ul>
<li>【选择排序】：最值出现在起始端</li>
<li>第1趟：在n个数中找到最小(大)数与第一个数交换位置</li>
<li>第2趟：在剩下n-1个数中找到最小(大)数与第二个数交换位置</li>
<li>重复这样的操作…依次与第三个、第四个…数交换位置</li>
<li>第n-1趟，最终可实现数据的升序（降序）排列。</li>
</ul>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">void</span> selectSort(<span class="built_in">int</span> *arr, <span class="built_in">int</span> length) &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="built_in">int</span> i = <span class="number">0</span>; i &lt; length - <span class="number">1</span>; i++) &#123; <span class="comment">//趟数</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="built_in">int</span> j = i + <span class="number">1</span>; j &lt; length; j++) &#123; <span class="comment">//比较次数</span></span><br><span class="line">            <span class="keyword">if</span> (arr[i] &gt; arr[j]) &#123;</span><br><span class="line">                <span class="built_in">int</span> temp = arr[i];</span><br><span class="line">                arr[i] = arr[j];</span><br><span class="line">                arr[j] = temp;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>4.2、冒泡排序</strong></p>
<ul>
<li>【冒泡排序】：相邻元素两两比较，比较完一趟，最值出现在末尾</li>
<li>第1趟：依次比较相邻的两个数，不断交换（小数放前，大数放后）逐个推进，最值最后出现在第n个元素位置</li>
<li>第2趟：依次比较相邻的两个数，不断交换（小数放前，大数放后）逐个推进，最值最后出现在第n-1个元素位置</li>
<li>……   ……</li>
<li>第n-1趟：依次比较相邻的两个数，不断交换（小数放前，大数放后）逐个推进，最值最后出现在第2个元素位置</li>
</ul>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">void</span> bublleSort(<span class="built_in">int</span> *arr, <span class="built_in">int</span> length) &#123;</span><br><span class="line">    <span class="keyword">for</span>(<span class="built_in">int</span> i = <span class="number">0</span>; i &lt; length - <span class="number">1</span>; i++) &#123; <span class="comment">//趟数</span></span><br><span class="line">        <span class="keyword">for</span>(<span class="built_in">int</span> j = <span class="number">0</span>; j &lt; length - i - <span class="number">1</span>; j++) &#123; <span class="comment">//比较次数</span></span><br><span class="line">            <span class="keyword">if</span>(arr[j] &gt; arr[j+<span class="number">1</span>]) &#123;</span><br><span class="line">                <span class="built_in">int</span> temp = arr[j];</span><br><span class="line">                arr[j] = arr[j+<span class="number">1</span>];</span><br><span class="line">                arr[j+<span class="number">1</span>] = temp;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="5、折半查找（二分查找）"><a href="#5、折半查找（二分查找）" class="headerlink" title="#### 5、折半查找（二分查找）"></a>#### 5、折半查找（二分查找）</h2><p>折半查找：优化查找时间（不用遍历全部数据）<br>折半查找的原理：</p>
<ul>
<li>1&gt; 数组必须是有序的</li>
<li>2&gt; 必须已知min和max（知道范围）</li>
<li>3&gt; 动态计算mid的值，取出mid对应的值进行比较</li>
<li>4&gt; 如果mid对应的值大于要查找的值，那么max要变小为mid-1</li>
<li>5&gt; 如果mid对应的值小于要查找的值，那么min要变大为mid+1</li>
</ul>
<p>// 已知一个有序数组, 和一个key, 要求从数组中找到key对应的索引位置</p>
<figure class="highlight processing"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">int</span> findKey(<span class="built_in">int</span> *arr, <span class="built_in">int</span> length, <span class="built_in">int</span> <span class="built_in">key</span>) &#123;</span><br><span class="line">    <span class="built_in">int</span> <span class="built_in">min</span> = <span class="number">0</span>, <span class="built_in">max</span> = length - <span class="number">1</span>, mid;</span><br><span class="line">    <span class="keyword">while</span> (<span class="built_in">min</span> &lt;= <span class="built_in">max</span>) &#123;</span><br><span class="line">        mid = (<span class="built_in">min</span> + <span class="built_in">max</span>) / <span class="number">2</span>; <span class="comment">//计算中间值</span></span><br><span class="line">        <span class="keyword">if</span> (<span class="built_in">key</span> &gt; arr[mid]) &#123;</span><br><span class="line">            <span class="built_in">min</span> = mid + <span class="number">1</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="built_in">key</span> &lt; arr[mid]) &#123;</span><br><span class="line">            <span class="built_in">max</span> = mid - <span class="number">1</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> mid;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="6、集合结构-线性结构-树形结构-图形结构"><a href="#6、集合结构-线性结构-树形结构-图形结构" class="headerlink" title="6、集合结构 线性结构 树形结构 图形结构"></a>6、集合结构 线性结构 树形结构 图形结构</h2><ul>
<li>1.1、集合结构 说白了就是一个集合，就是一个圆圈中有很多个元素，元素与元素之间没有任何关系  这个很简单</li>
<li>1.2、线性结构 说白了就是一个条线上站着很多个人。 这条线不一定是直的。也可以是弯的。也可以是值的 相当于一条线被分成了好几段的样子 （发挥你的想象力）。 线性结构是一对一的关系</li>
<li>1.3、树形结构 说白了  做开发的肯定或多或少的知道xml 解析  树形结构跟他非常类似。也可以想象成一个金字塔。树形结构是一对多的关系</li>
<li>1.4、图形结构 这个就比较复杂了。他呢 无穷。无边  无向（没有方向）图形机构 你可以理解为多对多 类似于我们人的交集关系</li>
</ul>
<h2 id="7、数据结构的存储"><a href="#7、数据结构的存储" class="headerlink" title="7、数据结构的存储"></a>7、数据结构的存储</h2><p>数据结构的存储一般常用的有两种   顺序存储结构 和 链式存储结构</p>
<ul>
<li>2.1  顺序存储结构</li>
</ul>
<p>发挥想象力啊。 举个列子。数组。1-2-3-4-5-6-7-8-9-10。这个就是一个顺序存储结构 ，存储是按顺序的  举例说明啊。 栈。做开发的都熟悉。栈是先进后出 ，后进先出的形式 对不对 ？！他的你可以这样理解</p>
<p>hello world 在栈里面从栈底到栈顶的逻辑依次为 h-e-l-l-o-w-o-r-l-d 这就是顺序存储 再比如 队列 ，队列是先进先出的对吧，从头到尾 h-e-l-l-o-w-o-r-l-d 就是这样排对的</p>
<ul>
<li>2.2 链式存储结构</li>
</ul>
<p>再次发挥想象力 这个稍微复杂一点 这个图片我一直弄好 ，回头找美工问问，再贴上  例如 还是一个数组</p>
<p>1-2-3-4-5-6-7-8-9-10  链式存储就不一样了 1(地址)-2(地址)-7(地址)-4(地址)-5(地址)-9(地址)-8(地址)-3(地址)-6(地址)-10(地址)。每个数字后面跟着一个地址 而且存储形式不再是顺序 ，也就说顺序乱了，1（地址） 1后面跟着的这个地址指向的是2，2后面的地址指向的是3，3后面的地址指向是谁你应该清楚了吧。他执行的时候是 1(地址)-2(地址)-3(地址)-4(地址)-5(地址)-6(地址)-7(地址)-8(地址)-9(地址)-10(地址)，但是存储的时候就是完全随机的。明白了？！</p>
<h2 id="8、单向链表-双向链表-循环链表"><a href="#8、单向链表-双向链表-循环链表" class="headerlink" title="8、单向链表\双向链表\循环链表"></a>8、单向链表\双向链表\循环链表</h2><p>还是举例子。理解最重要。不要去死记硬背 哪些什么。定义啊。逻辑啊。理解才是最重要滴</p>
<ul>
<li>3.1 单向链表</li>
</ul>
<p>A-&gt;B-&gt;C-&gt;D-&gt;E-&gt;F-&gt;G-&gt;H. 这就是单向链表 H 是头 A 是尾 像一个只有一个头的火车一样 只能一个头拉着跑<br><img src="https://upload-images.jianshu.io/upload_images/13252132-681296a63ca929e4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"></p>
<ul>
<li>3.2 双向链表</li>
</ul>
<p><img src="https://upload-images.jianshu.io/upload_images/13252132-b3d7480416c4f332.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"></p>
<blockquote>
<p>数组和链表区别：<br>数组：数组元素在内存上连续存放，可以通过下标查找元素；插入、删除需要移动大量元素，比较适用于元素很少变化的情况<br>链表：链表中的元素在内存中不是顺序存储的，查找慢，插入、删除只需要对元素指针重新赋值，效率高</p>
</blockquote>
<ul>
<li>3.3 循环链表</li>
</ul>
<p>循环链表是与单向链表一样，是一种链式的存储结构，所不同的是，循环链表的最后一个结点的指针是指向该循环链表的第一个结点或者表头结点，从而构成一个环形的链。发挥想象力  A-&gt;B-&gt;C-&gt;D-&gt;E-&gt;F-&gt;G-&gt;H-&gt;A. 绕成一个圈。就像蛇吃自己的这就是循环  不需要去死记硬背哪些理论知识。</p>
<h2 id="9、二叉树／平衡二叉树"><a href="#9、二叉树／平衡二叉树" class="headerlink" title="9、二叉树／平衡二叉树"></a>9、二叉树／平衡二叉树</h2><ul>
<li>4.1 什么是二叉树</li>
</ul>
<p>树形结构下,两个节点以内 都称之为二叉树 不存在大于2 的节点 分为左子树 右子树 有顺序 不能颠倒 ，懵逼了吧，你肯定会想这是什么玩意，什么左子树右子树 ，都什么跟什么鬼？  现在我以普通话再讲一遍，你把二叉树看成一个人 ，人的头呢就是树的根 ，左子树就是左手，右子树就是右手，左右手可以都没有（残疾嘛，声明一下，绝非歧视残疾朋友，勿怪，勿怪就是举个例子，i am very sorry）  , 左右手呢可以有一个，就是不能颠倒。这样讲应该明白了吧</p>
<p><strong>二叉树有五种表现形式</strong></p>
<p>1.空的树（没有节点）可以理解为什么都没 像空气一样<br>2.只有根节点。 （理解一个人只有一个头 其他的什么都没，说的有点恐怖）<br>3.只有左子树 （一个头 一个左手 感觉越来越写不下去了）<br>4.只有右子树<br>5.左右子树都有</p>
<p>二叉树可以转换成森林 树也可以转换成二叉树。这里就不介绍了 你做项目绝对用不到<br>数据结构大致介绍这么多吧。理解为主, 别死记，死记没什么用</p>
<h2 id=""><a href="#" class="headerlink" title=""></a></h2>
    </div>

    
    
    
        <div class="reward-container">
  <div>希望对您有所帮助，您的支持将是我莫大的动力！</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/blogwebpage/images/wechatpay.png" alt="Jack Wang 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/blogwebpage/images/alipay.png" alt="Jack Wang 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/blogwebpage/tags/iOS%E7%AE%97%E6%B3%95%E6%94%B6%E9%9B%86/" rel="tag"># iOS算法收集</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blogwebpage/iOS/block/index.html" rel="prev" title="Block相关知识点">
      <i class="fa fa-chevron-left"></i> Block相关知识点
    </a></div>
      <div class="post-nav-item">
    <a href="/blogwebpage/linux/home.html" rel="next" title="Linux">
      Linux <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81%E4%B8%8D%E7%94%A8%E4%B8%AD%E9%97%B4%E5%8F%98%E9%87%8F-%E7%94%A8%E4%B8%A4%E7%A7%8D%E6%96%B9%E6%B3%95%E4%BA%A4%E6%8D%A2A%E5%92%8CB%E7%9A%84%E5%80%BC"><span class="nav-number">1.</span> <span class="nav-text">1、不用中间变量,用两种方法交换A和B的值</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2%E3%80%81%E6%B1%82%E6%9C%80%E5%A4%A7%E5%85%AC%E7%BA%A6%E6%95%B0"><span class="nav-number">2.</span> <span class="nav-text">2、求最大公约数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3%E3%80%81%E6%A8%A1%E6%8B%9F%E6%A0%88%E6%93%8D%E4%BD%9C"><span class="nav-number">3.</span> <span class="nav-text">3、模拟栈操作</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4%E3%80%81%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95"><span class="nav-number">4.</span> <span class="nav-text">4、排序算法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5%E3%80%81%E6%8A%98%E5%8D%8A%E6%9F%A5%E6%89%BE%EF%BC%88%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%EF%BC%89"><span class="nav-number">5.</span> <span class="nav-text">#### 5、折半查找（二分查找）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6%E3%80%81%E9%9B%86%E5%90%88%E7%BB%93%E6%9E%84-%E7%BA%BF%E6%80%A7%E7%BB%93%E6%9E%84-%E6%A0%91%E5%BD%A2%E7%BB%93%E6%9E%84-%E5%9B%BE%E5%BD%A2%E7%BB%93%E6%9E%84"><span class="nav-number">6.</span> <span class="nav-text">6、集合结构 线性结构 树形结构 图形结构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7%E3%80%81%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E7%9A%84%E5%AD%98%E5%82%A8"><span class="nav-number">7.</span> <span class="nav-text">7、数据结构的存储</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8%E3%80%81%E5%8D%95%E5%90%91%E9%93%BE%E8%A1%A8-%E5%8F%8C%E5%90%91%E9%93%BE%E8%A1%A8-%E5%BE%AA%E7%8E%AF%E9%93%BE%E8%A1%A8"><span class="nav-number">8.</span> <span class="nav-text">8、单向链表\双向链表\循环链表</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#9%E3%80%81%E4%BA%8C%E5%8F%89%E6%A0%91%EF%BC%8F%E5%B9%B3%E8%A1%A1%E4%BA%8C%E5%8F%89%E6%A0%91"><span class="nav-number">9.</span> <span class="nav-text">9、二叉树／平衡二叉树</span></a></li><li class="nav-item nav-level-2"><a class="nav-link"><span class="nav-number">10.</span> <span class="nav-text"></span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Jack Wang"
      src="/blogwebpage/images/avatar.gif">
  <p class="site-author-name" itemprop="name">Jack Wang</p>
  <div class="site-description" itemprop="description">书山有路勤为径，学海无涯苦作舟！</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blogwebpage/archives/">
        
          <span class="site-state-item-count">52</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blogwebpage/categories/">
          
        <span class="site-state-item-count">56</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blogwebpage/tags/">
          
        <span class="site-state-item-count">54</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL0phY2stVmluZw==" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;Jack-Ving"><i class="github fa-fw"></i>GitHub</span>
      </span>
      <span class="links-of-author-item">
        <span class="exturl" data-url="bWFpbHRvOjcyNzg4MTk0NUBxcS5jb20=" title="E-Mail → mailto:727881945@qq.com"><i class="envelope fa-fw"></i>E-Mail</span>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        
  <div class="beian"><span class="exturl" data-url="aHR0cHM6Ly9iZWlhbi5taWl0Lmdvdi5jbg==">京ICP备16036665号-2 </span>
  </div>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Jack Wang</span>
</div>
  <div class="powered-by">由 <span class="exturl theme-link" data-url="aHR0cHM6Ly9oZXhvLmlv">Hexo</span> & <span class="exturl theme-link" data-url="aHR0cHM6Ly90aGVtZS1uZXh0Lm9yZw==">NexT.Gemini</span> 强力驱动
  </div>

        


  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1277804316&web_id=1277804316"></script>
  </div>






      </div>
    </footer>
  </div>

  
  <script src="/blogwebpage/lib/anime.min.js"></script>
  <script src="/blogwebpage/lib/velocity/velocity.min.js"></script>
  <script src="/blogwebpage/lib/velocity/velocity.ui.min.js"></script>

<script src="/blogwebpage/js/utils.js"></script>

<script src="/blogwebpage/js/motion.js"></script>


<script src="/blogwebpage/js/schemes/pisces.js"></script>


<script src="/blogwebpage/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/blogwebpage/js/local-search.js"></script>













  

  

</body>
</html>
